<template>
  <div
    class="app-container"
    style="min-height: calc(100vh - 128px); overflow: hidden"
  >
    <div class="search-container">
      <el-form :inline="true">
        <el-form-item :label="$t('correctwork.StudentenausweisName')">
          <el-input
            v-model="queryParams.name"
            :placeholder="$t('correctwork.Namenein')"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item :label="$t('correctwork.Klasseninformationen')">
          <el-select v-model="queryParams.className">
            <el-option v-for="dict in classList" :key="dict.id" :value="dict" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('correctwork.Zustand')">
          <el-select v-model="queryParams.status">
            <el-option
              v-for="dict in correct_experiment_status"
              :key="dict.value"
              :label="
                translateTagDictI18n('correct_experiment_status', dict.label)
              "
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button v-throttle="handleQuery" type="primary"
            ><el-icon style="margin-right: 5px; font-size: 18px"
              ><Search /></el-icon
            >{{ $t("correctwork.Suche") }}</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button v-throttle="resetting" type=""
            ><el-icon style="margin-right: 5px; font-size: 18px">
              <Refresh /> </el-icon
            >{{ $t("correctwork.Zurücksetzen") }}</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <div class="data">
      <el-card shadow="never">
        <template #header>
          <el-button
            class="mx-1"
            type=""
            plain
            style="color: var(--el-color-primary)"
          >
            <svg-icon
              icon-class="yitijiao"
              style="font-size: 20px; margin-right: 3px"
            ></svg-icon>
            {{ $t("correctwork.Eingereicht") }}
            {{ submittotal + correcttotal }}/{{ total }}
          </el-button>
          <el-button
            class="mx-1"
            type=""
            plain
            style="color: var(--el-color-success)"
          >
            <svg-icon
              icon-class="yipigai"
              style="font-size: 20px; margin-right: 3px"
            ></svg-icon
            >{{ $t("correctwork.Korrigiert1") }} {{ correcttotal }}/{{
              total
            }}</el-button
          >
          <div class="elbut">
            <el-button
              :key="1"
              v-throttle="gradexport"
              v-hasPerm="['correctinfo:correctwork:export']"
              class="Upload"
              type=""
              plain
            >
              <svg-icon
                :icon-class="'layout_upload'"
                style="margin-right: 5px; font-size: 18px"
              />{{ $t("correctwork.Ausfuhrzahlen") }}</el-button
            >
            <el-button
              :key="2"
              v-throttle="batchexport"
              v-hasPerm="['correctinfo:correctwork:download']"
              class="Upload"
              type=""
              :disabled="ids.length == 0"
              plain
            >
              <svg-icon
                :icon-class="'pl_upload'"
                style="margin-right: 5px; font-size: 18px"
              />{{ $t("correctwork.Stapelexportbericht") }}</el-button
            >
            <el-button
              :key="3"
              v-throttle="() => downloadall(null)"
              v-hasPerm="['correctinfo:correctwork:download']"
              type=""
              class="Upload"
              plain
            >
              <svg-icon
                :icon-class="'correct_upload'"
                style="margin-right: 5px; font-size: 18px"
              />{{ $t("correctwork.herunterladen") }}</el-button
            >
          </div>
        </template>

        <el-table
          v-loading="tabloading"
          border
          :data="experimentList"
          empty-text="暂无提交信息"
          @selection-change="handleSelectionChange"
        >
          <el-table-column fixed type="selection" width="55" align="center">
          </el-table-column>
          <el-table-column
            :label="$t('correctwork.Name')"
            prop="nickname"
            align="center"
          ></el-table-column>
          <el-table-column
            :label="$t('correctwork.Studentenausweis')"
            prop="codeId"
            align="center"
          >
            <template #default="scope">
              <el-text
                v-if="scope.row.codeId == null"
                style="opacity: 0.8; font-size: 12px; margin: 0 auto"
                >暂无学号</el-text
              >
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('correctwork.Klasse')"
            prop="className"
            align="center"
            :show-overflow-tooltip="true"
            style="
              overflow: hidden;
              white-space: nowrap;
              text-overflow: ellipsis;
            "
          >
            <template #default="scope">
              <el-text
                v-if="scope.row.className == null"
                style="opacity: 0.8; font-size: 12px; margin: 0 auto"
                >暂无班级</el-text
              >
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('correctwork.Einreichungsdatum')"
            prop="createTime"
            align="center"
            width="180px"
          >
            <template #default="scope">
              <el-text
                v-if="scope.row.status === 0"
                style="opacity: 0.8; font-size: 12px; margin: 0 auto"
                >暂未提交</el-text
              >
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('correctwork.Einreichungsstatus')"
            prop="status"
            align="center"
            width="180px"
          >
            <template #default="scope">
              <el-button
                v-if="scope.row.status === 2 || scope.row.status === 1"
                type="success"
                plain
                size="small"
                >已提交</el-button
              >

              <el-button
                v-if="scope.row.status === 0"
                type="info"
                plain
                size="small"
                >{{ scope.row.statusLabel }}</el-button
              >
              <el-button
                v-if="scope.row.status === 3"
                type="danger"
                plain
                size="small"
                >已驳回</el-button
              >
              <el-button
                v-if="
                  scope.row.status === 1 ||
                  scope.row.status === 2 ||
                  scope.row.status === 3
                "
                v-throttle="() => preview(scope.row)"
                type="warning"
                plain
                size="small"
              >
                {{ $t("correctwork.Vorschau") }}</el-button
              >
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('correctwork.Korrekturstatus')"
            prop="grade"
            align="center"
            width="180px"
          >
            <template #default="scope">
              <el-button
                v-if="scope.row.status === 2 && scope.row.status != 3"
                type="success"
                plain
                size="small"
                >已批改 {{ scope.row.grade }} 分</el-button
              >
              <el-button
                v-if="
                  (scope.row.status != 2 && scope.row.status != 3) ||
                  scope.row.status === 0
                "
                type="warning"
                plain
                size="small"
                >未批改</el-button
              >
              <el-button
                v-if="scope.row.status === 3"
                type="danger"
                plain
                size="small"
                >已驳回</el-button
              >
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('correctwork.Betrieb')"
            align="center"
            width="280px"
          >
            <template #default="scope">
              <el-button
                v-if="scope.row.status === 2"
                v-hasPerm="['correctinfo:correctwork:correct']"
                type="primary"
                link
                @click="correct(1, scope.row)"
              >
                <el-icon size="18px">
                  <EditPen />
                </el-icon>
                {{ $t("correctwork.Überarbeiten") }}
              </el-button>
              <el-button
                v-if="scope.row.status === 1"
                v-hasPerm="['correctinfo:correctwork:correct']"
                type="primary"
                link
                @click="correct(0, scope.row)"
              >
                <el-icon size="18px">
                  <EditPen />
                </el-icon>
                {{ $t("correctwork.Korrektur") }}
              </el-button>
              <el-button
                v-if="scope.row.status === 1 || scope.row.status === 2"
                v-throttle="() => downloadall(scope.row.userId)"
                v-hasPerm="['correctinfo:correctwork:download']"
                type="primary"
                link
              >
                <el-icon size="18px">
                  <Download />
                </el-icon>
                {{ $t("correctwork.Download") }}
              </el-button>
              <el-button
                v-if="scope.row.status === 0 || scope.row.status === 3"
                link
              >
                {{ $t("correctwork.DerzeitBetrieb") }}</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-if="total > 0"
          v-model:total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handleQuery"
        />
      </el-card>
      <el-drawer
        v-model="drawer"
        size="100%"
        :show-close="false"
        @close="handClose"
      >
        <template #header="{ close, titleId, titleClass }">
          <div style="width: 100%; display: flex; height: 10px">
            <h1 :id="titleId" :class="titleClass">
              {{ correctRow.className + "-" + correctRow.nickname }}
            </h1>
            <el-button
              plain
              style="font-size: 26px; color: var(--el-color-danger)"
              @click="close"
            >
              <svg-icon icon-class="co_pigai"></svg-icon>
            </el-button>
          </div>
        </template>
        <template #default>
          <el-row style="width: 100%; margin-top: -35px" :gutter="10">
            <el-col :span="8">
              <div class="left" style="height: 100px">
                <h3>{{ $t("correctwork.Dateiliste") }}</h3>
                <el-table
                  align="left"
                  empty-text="暂无文件信息"
                  :data="experimentFileslist"
                  @row-click="1"
                >
                  <el-table-column
                    :label="$t('correctwork.Dateiname')"
                    prop="name"
                    :show-overflow-tooltip="true"
                    style="
                      white-space: nowrap;
                      overflow: hidden;
                      text-overflow: ellipsis;
                    "
                  >
                    <template #default="scope">
                      <svg-icon
                        :icon-class="scope.row.name.split('.').at(-1)"
                        style="
                          font-size: 24px;
                          margin-right: 5px;
                          vertical-align: middle;
                        "
                      />
                      {{ scope.row.name }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    :label="$t('correctwork.Betrieb')"
                    width="90px"
                  >
                    <template #default="scope">
                      <el-tooltip
                        :content="$t('correctwork.Vorschau')"
                        placement="bottom"
                        effect="light"
                      >
                        <svg-icon
                          :icon-class="'perview'"
                          style="
                            font-size: 20px;
                            text-align: right;
                            vertical-align: middle;
                            margin-right: 5px;
                            color: var(--el-color-primary);
                          "
                          @click="previewfile(scope.row.url)"
                        />
                      </el-tooltip>
                      <el-tooltip
                        :content="$t('correctwork.Download')"
                        placement="bottom"
                        effect="light"
                      >
                        <svg-icon
                          :icon-class="'correct_upload'"
                          style="
                            margin-left: 14px;
                            font-size: 18px;
                            line-height: 18px;
                            vertical-align: middle;
                            color: var(--el-color-primary);
                          "
                          class="operation_class"
                          @click="
                            handleDownload(scope.row.path, scope.row.name)
                          "
                        />
                      </el-tooltip>
                    </template>
                  </el-table-column>
                </el-table>
                <h3>{{ $t("correctwork.Überprüfungsinformationen") }}</h3>
                <el-table
                  align="left"
                  empty-text="暂无查重文件信息"
                  :data="duplicateFileInfoslist"
                >
                  <el-table-column
                    :label="$t('correctwork.Dateiname')"
                    prop="duplicateFile.name"
                    show-overflow-tooltip
                    style="
                      white-space: nowrap;
                      overflow: hidden;
                      text-overflow: ellipsis;
                    "
                  >
                    <template #default="scope">
                      <svg-icon
                        :icon-class="
                          scope.row.duplicateFile.name.split('.').at(-1)
                        "
                        style="
                          font-size: 24px;
                          margin-right: 5px;
                          vertical-align: middle;
                        "
                      />
                      {{ scope.row.duplicateFile.name }}
                    </template>
                  </el-table-column>

                  <el-table-column
                    :label="$t('correctwork.Duplikationsrate')"
                    prop="repetition"
                    width="160px"
                    :show-overflow-tooltip="true"
                  >
                    <template #default="scope">
                      <el-text
                        style="margin: 0; padding: 0"
                        :type="
                          Number(
                            scope.row.repetition.substring(
                              0,
                              scope.row.repetition.lastIndexOf('%')
                            )
                          ) < 30
                            ? 'success'
                            : 'danger'
                        "
                        >{{ scope.row.repetition }}</el-text
                      >
                    </template>
                  </el-table-column>
                  <el-table-column
                    :label="$t('correctwork.Betrieb')"
                    width="90px"
                  >
                    <template #default="scope">
                      <el-tooltip
                        :content="$t('correctwork.Vorschau')"
                        placement="bottom"
                        effect="light"
                      >
                        <svg-icon
                          :class="
                            !scope.row.duplicateFile.url ? 'disabled-icon' : ''
                          "
                          :icon-class="'perview'"
                          style="
                            font-size: 20px;
                            text-align: right;
                            vertical-align: middle;
                            margin-right: 5px;
                            color: var(--el-color-primary);
                          "
                          @click="previewfile(scope.row.duplicateFile.url)"
                        />
                      </el-tooltip>
                      <el-tooltip
                        :content="$t('correctwork.Download')"
                        placement="bottom"
                        effect="light"
                      >
                        <svg-icon
                          :class="
                            scope.row.duplicateFile.path == null
                              ? 'disabled-icon'
                              : ''
                          "
                          :icon-class="'correct_upload'"
                          style="
                            margin-left: 14px;
                            font-size: 18px;
                            line-height: 18px;
                            vertical-align: middle;
                            color: var(--el-color-primary);
                          "
                          @click="
                            handleDownload(
                              scope.row.duplicateFile.path,
                              scope.row.duplicateFile.name
                            )
                          "
                        />
                      </el-tooltip>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-col>
            <el-col :span="16">
              <div class="center">
                <h3>{{ $t("correctwork.Vorschautext") }}</h3>
                <iframe
                  v-if="previewURL"
                  id="iframe"
                  :src="previewURL"
                  style="
                    width: 100%;
                    height: calc(100vh - 140px);
                    padding-left: -100px;
                  "
                >
                </iframe>
                <svg-icon
                  v-else
                  :icon-class="'yulanch'"
                  style="
                    width: 100%;
                    height: calc(100vh - 140px);
                    /* margin-top: -75px; */
                  "
                />
              </div>
            </el-col>
          </el-row>
        </template>
      </el-drawer>
      <el-drawer
        v-model="correctdrawer"
        size="100%"
        :show-close="false"
        @close="handClose"
      >
        <template #header="{ close, titleId, titleClass }">
          <div style="width: 100%; display: flex; height: 10px">
            <h1 :id="titleId" :class="titleClass">
              {{ correctRow.className + "-" + correctRow.nickname }}
            </h1>
            <el-button
              style="font-size: 26px; color: var(--el-color-danger)"
              plain
              @click="close"
            >
              <svg-icon icon-class="co_pigai"></svg-icon>
            </el-button>
          </div>
        </template>
        <template #default>
          <local-loading :loading="correctLoading"></local-loading>
          <el-row
            v-if="!correctLoading"
            style="width: 100%; margin-top: -35px"
            :gutter="10"
          >
            <el-col :span="left">
              <div class="left" style="height: 100px">
                <h3>{{ $t("correctwork.Dateiliste") }}</h3>
                <el-table
                  align="left"
                  empty-text="暂无文件信息"
                  :data="experimentFileslist"
                  @row-click="1"
                >
                  <el-table-column
                    :label="$t('correctwork.Dateiname')"
                    prop="name"
                    :show-overflow-tooltip="true"
                    style="
                      white-space: nowrap;
                      overflow: hidden;
                      text-overflow: ellipsis;
                    "
                  >
                    <template #default="scope">
                      <svg-icon
                        :icon-class="scope.row.name.split('.').at(-1)"
                        style="
                          font-size: 24px;
                          margin-right: 5px;
                          vertical-align: middle;
                        "
                      />
                      {{ scope.row.name }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    :label="$t('correctwork.Betrieb')"
                    width="90px"
                  >
                    <template #default="scope">
                      <el-tooltip
                        :content="$t('correctwork.Vorschau')"
                        placement="bottom"
                        effect="light"
                      >
                        <svg-icon
                          :icon-class="'perview'"
                          style="
                            font-size: 20px;
                            text-align: right;
                            vertical-align: middle;
                            margin-right: 5px;
                            color: var(--el-color-primary);
                          "
                          @click="previewfile(scope.row.url)"
                        />
                      </el-tooltip>
                      <el-tooltip
                        :content="$t('correctwork.Download')"
                        placement="bottom"
                        effect="light"
                      >
                        <svg-icon
                          :icon-class="'correct_upload'"
                          style="
                            margin-left: 14px;
                            font-size: 18px;
                            line-height: 18px;
                            vertical-align: middle;
                            color: var(--el-color-primary);
                          "
                          class="operation_class"
                          @click="
                            handleDownload(scope.row.path, scope.row.name)
                          "
                        />
                      </el-tooltip>
                    </template>
                  </el-table-column>
                </el-table>
                <h3>{{ $t("correctwork.Überprüfungsinformationen") }}</h3>
                <el-table
                  align="left"
                  empty-text="暂无查重文件信息"
                  :data="duplicateFileInfoslist"
                >
                  <el-table-column
                    :label="$t('correctwork.Dateiname')"
                    prop="duplicateFile.name"
                    show-overflow-tooltip
                    style="
                      white-space: nowrap;
                      overflow: hidden;
                      text-overflow: ellipsis;
                    "
                  >
                    <template #default="scope">
                      <svg-icon
                        :icon-class="
                          scope.row.duplicateFile.name.split('.').at(-1)
                        "
                        style="
                          font-size: 24px;
                          margin-right: 5px;
                          vertical-align: middle;
                        "
                      />
                      {{ scope.row.duplicateFile.name }}
                    </template>
                  </el-table-column>

                  <el-table-column
                    :label="$t('correctwork.Duplikationsrate')"
                    prop="repetition"
                    width="160px"
                    :show-overflow-tooltip="true"
                  >
                    <template #default="scope">
                      <el-text
                        style="margin: 0; padding: 0"
                        :type="
                          Number(
                            scope.row.repetition.substring(
                              0,
                              scope.row.repetition.lastIndexOf('%')
                            )
                          ) < 30
                            ? 'success'
                            : 'danger'
                        "
                        >{{ scope.row.repetition }}</el-text
                      >
                    </template>
                  </el-table-column>
                  <el-table-column
                    :label="$t('correctwork.Betrieb')"
                    width="90px"
                  >
                    <template #default="scope">
                      <el-tooltip
                        :content="$t('correctwork.Vorschau')"
                        placement="bottom"
                        effect="light"
                      >
                        <svg-icon
                          :class="
                            !scope.row.duplicateFile.url ? 'disabled-icon' : ''
                          "
                          :icon-class="'perview'"
                          style="
                            font-size: 20px;
                            text-align: right;
                            vertical-align: middle;
                            margin-right: 5px;
                            color: var(--el-color-primary);
                          "
                          @click="previewfile(scope.row.duplicateFile.url)"
                        />
                      </el-tooltip>
                      <el-tooltip
                        :content="$t('correctwork.Download')"
                        placement="bottom"
                        effect="light"
                      >
                        <svg-icon
                          :class="
                            scope.row.duplicateFile.path == null
                              ? 'disabled-icon'
                              : ''
                          "
                          :icon-class="'correct_upload'"
                          style="
                            margin-left: 14px;
                            font-size: 18px;
                            line-height: 18px;
                            vertical-align: middle;
                            color: var(--el-color-primary);
                          "
                          @click="
                            handleDownload(
                              scope.row.duplicateFile.path,
                              scope.row.duplicateFile.name
                            )
                          "
                        />
                      </el-tooltip>
                    </template>
                  </el-table-column>
                </el-table>
                <h3>{{ $t("correctwork.Punktkorrektur") }}</h3>
                <el-form
                  ref="formLabel"
                  label-position="right"
                  label-width="70"
                  :model="formLabelAlign"
                  style="margin: 0 auto"
                  :rules="rules"
                >
                  <el-form-item
                    :label="$t('correctwork.Bruch')"
                    style="font-weight: bolder"
                    prop="grade"
                  >
                    <el-input
                      v-model="formLabelAlign.grade"
                      :placeholder="$t('correctwork.Partiturein')"
                      @input="handleInput"
                    />
                  </el-form-item>
                  <el-form-item
                    :label="$t('correctwork.Kommentar')"
                    style="font-weight: bolder"
                  >
                    <el-input
                      v-model="formLabelAlign.comment"
                      :rows="3"
                      type="textarea"
                      :placeholder="$t('correctwork.Kommentarein')"
                    />
                  </el-form-item>
                  <div
                    style="width: 100%; display: flex; justify-content: center"
                  >
                    <el-button
                      v-throttle="scoreCorrection"
                      type=""
                      size="large"
                      style="font-size: 16px; color: var(--el-color-primary)"
                    >
                      <svg-icon
                        :icon-class="'pigai'"
                        style="margin-right: 5px; font-size: 20px"
                      />
                      {{ $t("correctwork.Korrekturtext") }}</el-button
                    >
                    <el-button
                      v-throttle="overRuled"
                      type=""
                      size="large"
                      style="font-size: 16px; color: var(--el-color-danger)"
                    >
                      <svg-icon
                        :icon-class="'backtask'"
                        style="margin-right: 5px; font-size: 18px"
                      />
                      {{ $t("correctwork.Ablehnen") }}</el-button
                    >
                  </div>
                </el-form>
              </div>
            </el-col>
            <el-col :span="center">
              <div class="center">
                <h3>{{ $t("correctwork.Vorschautext") }}</h3>
                <iframe
                  v-if="previewURL"
                  id="iframe"
                  :src="previewURL"
                  style="
                    width: 100%;
                    height: calc(100vh - 140px);
                    padding-left: -100px;
                  "
                >
                </iframe>
                <svg-icon
                  v-else
                  :icon-class="'yulanch'"
                  style="
                    width: 100%;
                    height: calc(100vh - 140px);
                    /* margin-top: -75px; */
                  "
                />
              </div>
            </el-col>
            <el-col :span="right">
              <div class="right">
                <h3>{{ $t("correctwork.Überprüfungsregeln") }}</h3>
                <el-table
                  :height="calculatedValue"
                  :data="templateRuleFormData"
                  highlight-current-row
                  :tree-props="{
                    children: 'children',
                    hasChildren: 'hasChildren',
                  }"
                  row-key="id"
                  default-expand-all
                  border
                  size="small"
                >
                  <el-table-column
                    :label="$t('correctwork.Regelname')"
                    align="left"
                    prop="name"
                    :show-overflow-tooltip="true"
                  >
                    <template #default="scope">
                      <el-radio-group
                        v-if="scope.row.type === RuleTypeEnum.RULE"
                        v-model="gradetotal[grades(scope.row.id)]"
                        @change="handchange"
                      >
                        <el-radio :label="scope.row.id">{{
                          scope.row.name
                        }}</el-radio>
                      </el-radio-group>
                    </template>
                  </el-table-column>
                  <el-table-column
                    :label="$t('correctwork.Typ')"
                    align="center"
                    prop="type"
                    fixed="right"
                    width="70"
                  >
                    <template #default="scope">
                      <el-tag
                        v-if="scope.row.type === RuleTypeEnum.CALLED"
                        type="warning"
                        >总称</el-tag
                      >
                      <el-tag
                        v-if="scope.row.type === RuleTypeEnum.BRANCH"
                        type="success"
                        >分支</el-tag
                      >
                      <el-tag
                        v-if="scope.row.type === RuleTypeEnum.RULE"
                        type="danger"
                        >规则</el-tag
                      >
                    </template>
                  </el-table-column>
                  <el-table-column
                    :label="$t('correctwork.Bruch')"
                    align="center"
                    width="100"
                    fixed="right"
                    prop="grades"
                  />
                </el-table>
              </div>
            </el-col>
          </el-row>
        </template>
      </el-drawer>
    </div>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Correctwork",
  inheritAttrs: false,
});

import { translateTagDictI18n } from "@/utils/i18n";
import {
  downloadReportsExperiment,
  getExperimentPageOf,
  markingofresults,
  againmarkingofresults,
  numberQuery,
  rulesQuery,
  exportexperiment,
  getClassInfo,
  reportdiSmissed,
  continuousCorrect,
} from "@/api/experiment";
import {
  ExperimentQuery,
  SysFile,
  SysUserCourseFile,
  DuplicateFileInfo,
  MarkingRequest,
} from "@/api/experiment/types";
import { stringToBase64 } from "@/utils/btoa";
import { downloadFile } from "@/api/file";
import { downloadBlob } from "@/utils/file";
import { useRoute } from "vue-router";
import { RuleForm } from "@/api/rule/types";
import { RuleTypeEnum } from "@/enums/RuleTypeEnum";
import { ClassPageVO } from "@/api/class/types";
import { useCorrectStore } from "@/store/modules/correct";
import { useWindowSize } from "@vueuse/core";
import pagination from "@/components/Pagination/index.vue";
import LocalLoading from "@/components/LocalLoading/index.vue";

const { height } = useWindowSize();
const calculatedValue = ref(0);
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { correct_experiment_status } = proxy?.useDict(
  "correct_experiment_type",
  "correct_experiment_status"
);
const left = ref(6);
const center = ref(12);
const right = ref(6);
const ids = ref([]);
const tabloading = ref(false);
const correctLoading = ref(false);
const drawer = ref(false);
const correctdrawer = ref(false);
const route = useRoute();
const previewURL = ref("");
const ruleComment = ref("");
const experimentId = ref(Number(route.query.experimentId));
const experimentList = ref<SysUserCourseFile[]>();
const experimentFileslist = ref<SysFile[]>();
const duplicateFileInfoslist = ref<DuplicateFileInfo[]>();
const total = ref(0);
const correcttotal = ref(0);
const submittotal = ref(0);
const gradetotal = ref<number[]>([]);
const correctuserId = ref(0);
const formLabelAlign = reactive<MarkingRequest>({});
const templateRuleFormData = ref<RuleForm[]>([]);
const correctRow = ref<SysUserCourseFile>({});
const templateRuleFormDataLength = ref(0);
const correctStore = useCorrectStore();
const formLabel = ref(ElForm);
const classList = ref<ClassPageVO[]>();
const queryParams = reactive<ExperimentQuery>({
  pageNum: 1,
  pageSize: 10,
  experimentId: experimentId.value,
});
const rules = reactive({
  grade: [{ required: true, message: "分数不能为空", trigger: "blur" }],
});

// 行checkbox
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.userId);
}
// 计算属性求和
function grades(id: number) {
  const parentLevel = findParentLevel(
    templateRuleFormData.value![0].children!,
    id
  );
  return Number(parentLevel) - 1;
}
// 父标签
function findParentLevel(data: RuleForm[], targetId: number): number | null {
  for (let i = 0; i < data.length; i++) {
    const node = data[i];
    const found = findNodeInTree(node, targetId);
    if (found !== null) {
      return i + 1;
    }
  }
  return null;
}
// 树
function findNodeInTree(node: RuleForm, targetId: number): RuleForm | null {
  if (node.id === targetId) {
    return node as RuleForm;
  } else if (node.children) {
    for (const child of node.children) {
      const found = findNodeInTree(child, targetId);
      if (found !== null) {
        return found;
      }
    }
  }
  return null;
}
// 改变位置获取分数
function handchange(e: any) {
  const data = templateRuleFormData.value[0].children;
  ruleComment.value = "";
  formLabelAlign.grade = 0;
  for (let i = 0; i < gradetotal.value.length; i++) {
    for (let o = 0; o < data.length; o++) {
      for (let m = 0; m < data[o].children.length; m++) {
        if (data[o].children[m].id == gradetotal.value[i]) {
          formLabelAlign.grade += data[o].children[m].grades!;
          if (i == 0) {
            ruleComment.value += data[o].children[m].name!;
          } else {
            ruleComment.value += "；" + data[o].children[m].name!;
          }
          break;
        }
      }
    }
  }
}
// 查询
function handleQuery() {
  numberQuery(experimentId.value).then(({ data }) => {
    correcttotal.value = data.correct;
    submittotal.value = data.submit;
  });
  tabloading.value = true;
  getExperimentPageOf(queryParams)
    .then(({ data }) => {
      experimentList.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      tabloading.value = false;
    });
}
// 成绩导出
function gradexport() {
  exportexperiment(experimentId.value, correctStore.taskName)
    .then((response: any) => {
      downloadBlob(response);
    })
    .finally(() => {
      ElMessage.success("成绩导出成功，请稍后");
    });
}
// 批量导出
function batchexport(id?: number) {
  const userIds = [id || ids.value].join(",");
  if (!userIds) {
    ElMessage.warning("请勾选下载项");
    return;
  }
  downloadReportsExperiment(experimentId.value, userIds)
    .then((response) => {
      downloadBlob(response);
    })
    .catch((err) => {})
    .finally(() => {
      ElMessage.success("实验下载成功,请稍后");
    });
}
// 单击下载一个文件
function handleDownload(filePath: any, fileName: any) {
  downloadFile(filePath, fileName)
    .then((response) => {
      downloadBlob(response);
    })
    .finally(() => {
      ElMessage.success("实验下载成功,请稍后");
    });
}
// 预览文件信息
function preview(row: any) {
  experimentFileslist.value = row.experimentFiles;
  duplicateFileInfoslist.value = row.duplicateFileInfos;
  correctRow.value = row;
  drawer.value = true;
}
// 一键下载全部实验信息（包括个人文件 打包成文件夹信息）
function downloadall(useId: any) {
  downloadReportsExperiment(experimentId.value, useId)
    .then((response) => {
      downloadBlob(response);
    })
    .catch((err) => {})
    .finally(() => {
      ElMessage.success("实验下载成功,请稍后");
    });
}
//  点击批改信息
function correct(flag: number, row: any) {
  // 判断是否是重新批改
  if (flag) {
    // 获取重新批改后的(分数 和 评语信息)
    againmarkingofresults(row.id).then(({ data }) => {
      formLabelAlign.grade = data.grade;
      formLabelAlign.comment = data.comment;
    });
  }

  correctRow.value = row;
  correctuserId.value = row.id;
  experimentFileslist.value = row.experimentFiles;
  duplicateFileInfoslist.value = row.duplicateFileInfos;

  rulesQuery(experimentId.value).then(({ data }) => {
    gradetotal.value = [];
    templateRuleFormData.value = data;
    templateRuleFormDataLength.value = data[0].children.length;
    for (let i = 0; i < templateRuleFormDataLength.value; i++) {
      gradetotal.value.push(0);
    }
  });
  correctdrawer.value = true;
}
// 分数变化
function handleInput() {
  gradetotal.value = gradetotal.value.map(() => 0);
}
// 点击进行文件预览
function previewfile(filePath: any) {
  const str = stringToBase64(filePath);
  previewURL.value = `http://1.116.4.57:8012/onlinePreview?url=${str}`;
}
// 批改成绩
function scoreCorrection() {
  formLabel.value.validate((valid: boolean) => {
    if (valid) {
      ElMessageBox.confirm("确认提交该成绩信息?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(function () {
        correctLoading.value = true;

        if (
          formLabelAlign.comment?.trim() === "" ||
          formLabelAlign.comment == null
        ) {
          formLabelAlign.comment = ruleComment.value;
        }

        markingofresults(correctuserId.value, formLabelAlign)
          .then(() => {
            ElMessage.success("批改成功!");
            handleQuery();
            continuousCorrect(experimentId.value)
              .then(({ data }) => {
                correctRow.value = data;
                correctuserId.value = data.id!;
                experimentFileslist.value = data.experimentFiles;
                duplicateFileInfoslist.value = data.duplicateFileInfos;
                formLabelAlign.comment = "";
                formLabelAlign.grade = undefined;
              })
              .catch(() => {
                // ElMessage.success("所有任务已批改完成");
                correctdrawer.value = false;
              })
              .finally(() => {
                correctLoading.value = false;
              });
          })
          .finally(() => {
            correctLoading.value = false;
          });
      });
    } else {
    }
  });
}
// 关闭弹窗 清空预览信息
function handClose() {
  previewURL.value = "";
  formLabelAlign.grade = 0;
  formLabelAlign.comment = "";
  gradetotal.value = [];
}
// 获取当前任务id班级信息函数
function getclassinfo() {
  getClassInfo(experimentId.value).then(({ data }) => {
    classList.value = data;
  });
}
// 驳回
function overRuled() {
  ElMessageBox.confirm("确认驳回该报告?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    reportdiSmissed(correctuserId.value).then((res) => {
      ElMessage.success("驳回成功!");
      correctdrawer.value = false;
      handleQuery();
    });
  });
}
// 重置函数
function resetting() {
  queryParams.status = "" as unknown as number;
  queryParams.className = "";
  queryParams.name = "";
  formLabelAlign.grade = 0;
  handleQuery();
}
// 监听
watch(
  () => height.value,
  (newValue: any, oldValue: any) => {
    calculatedValue.value = newValue - 140;
  },
  { immediate: true }
);
// 进来就搜
onMounted(() => {
  handleQuery();
  getclassinfo();
});
</script>

<style scoped>
.elbut {
  display: flex;
  justify-content: end;
}
.Upload {
  align-items: center;
  vertical-align: middle;
  text-align: center;
  margin-top: -34px;
  color: var(--el-color-primary);
}
.disabled-icon {
  opacity: 0.4;
  /* 设置不透明度为0.5，使图标变暗 */
  /* 或者改变颜色为灰色 */
  fill: gray;
  cursor: no-drop;
  pointer-events: none;
  /* 禁用鼠标事件，使图标不可点击 */
}
.disabled-icon:hover {
  cursor: no-drop;
}
.section {
  padding-left: 600px;
  box-shadow: 0 0 0 1px #eee;
}
.section::after {
  content: "";
  display: block;
  clear: both;
}
.section > div {
  height: 100%;
  line-height: 1.5em;
  text-align: center;
  float: left;
  /* color: black; */
}
.sectioncorrect::after {
  content: "";
  display: block;
  clear: both;
}
.sectioncorrect > div {
  height: 100%;
  line-height: 1.5em;
  text-align: center;
  float: left;
  /* color: black; */
}
.sectioncorrect .left {
  position: relative;
  width: 34rem;
  left: -35rem;
  margin-left: -100%;
}
.sectioncorrect .right {
  position: relative;
  width: 34rem;
  left: 35rem;
  margin-left: -34rem;
}
.sectioncorrect .center {
  width: 100%;
  text-align: justify;
  hyphens: auto;
}
.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}
.tj {
  padding: 0px 20px 10px 20px;
  width: 100%;
  text-align: right;
  font-size: 14px;
  color: #808080;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bolder;
  padding: 0;
  margin: 0;
}
.text {
  padding: 0rem 20px;
  font-size: 14px;
}
.box-card {
  background: var(--el-bg-color-overlay);
}
:deep(el-card__header) {
  padding: 10px 20px;
}
.el-text {
  margin-left: 20px;
  font-weight: bold;
}
.button {
  border-radius: 15px;
}
.example-pagination-block {
  margin: 15px auto;
}
</style>
